package com.burst.reptile.modular.zp.service.impl;

import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.entity.ZpVote;
import com.burst.reptile.modular.zp.mapper.ZpResourcesMapper;
import com.burst.reptile.modular.zp.mapper.ZpVoteMapper;
import com.burst.reptile.modular.zp.service.IZpVoteService;

import lombok.RequiredArgsConstructor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户点赞列表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-06-16
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpVoteServiceImpl extends ServiceImpl<ZpVoteMapper, ZpVote> implements IZpVoteService {
	
	private final ZpResourcesMapper resourcesMapper;

	@Override
	@Transactional
	public int add(Long userId, ZpResources resources) {
		int count = this.count(new QueryWrapper<ZpVote>().eq("user_id", userId).eq("article_id", resources.getArticleId()));
		if(count > 0) {
			return 0;
		}
		ZpVote vote = new ZpVote();
		vote.setArticleId(resources.getArticleId());
		vote.setAuthorId(resources.getUserId());
		vote.setCoverImage(resources.getCoverImage());
		vote.setSummary(resources.getSummary());
		vote.setTitle(resources.getTitle());
		vote.setUserId(userId);
		// 累计文章点赞数量
		resourcesMapper.incrVote(resources.getArticleId());
		return this.baseMapper.insert(vote);
	}

	@Override
	@Transactional
	public int del(Long userId, Long articleId) {
		resourcesMapper.decrVote(articleId);
		return this.baseMapper.delete(new QueryWrapper<ZpVote>().eq("user_id", userId).eq("article_id", articleId));
	}

	@Override
	public Page<ZpVote> pageList(Page<ZpVote> page, ZpVote vote) {
		Long userId = vote.getUserId();
		QueryWrapper<ZpVote> queryWrapper = new QueryWrapper<>();
		if(ToolUtil.isNotEmpty(userId)) {
			queryWrapper.eq("user_id", userId);
		}
		queryWrapper.orderByDesc("create_time");
		return this.page(page, queryWrapper);
	}

}
